<template>
  <div>
    <!-- 返利池查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>
    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="wkcRepayRecordsImport"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <template slot="controls">
          <!-- <multiuse-button size="small" type="primary" @click="addHandle(1)">导 出</multiuse-button> -->
          <multiuse-button size="small" type="primary" @click="importHandler">导入</multiuse-button>
        </template>
      </FilterTables>
    </Spin>
    <BaseDialog :visible.sync="isAllDetail" :title="'开票车辆明细'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AllDetail :rowData="detailData" @close="detailclose" />
    </BaseDialog>
    <BaseDialog :visible.sync="isRepayDetail" :title="'开票还款车辆明细'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <RepayDetail :rowData="detailData" @close="detailclose1" />
    </BaseDialog>
    <!-- 导入 -->
    <BaseDialog :visible.sync="isImport" title="数据导入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ImportFile :rowData="formData" @close="emitCloseHandler2" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryList } from '@/api/omFinanceP/FinanceManage/RepayRecordsImport';
import { exportExcelFile } from '@/utils';
import { region } from '@/api/cms-common/region'; //行政区域
import { getRegion, getCommunity, getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index'; //事业部，办事处
import { dealerCommon, DICT_CODE } from '@/api/cms-api/origin/commonDealerType'; //经销商类型工具类
import ImportFile from './ImportFile';
import AllDetail from './AllDetail';
import RepayDetail from './RepayDetail';
export default {
  name: 'RepayRecordsImport',
  mixins: [dictionary, region, dealerCommon],
  data() {
    this.BaseTable = null;
    return {
      ORG_TYPE_MARKETING_WAR_AREA: 15061015, // 营销战区
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      exportLoading: false,
      formData: {},
      detailData: {},
      selectList: [],
      visible: false,
      isClick: false,
      isAllDetail: false,
      isRepayDetail: false,
      isImport: false,
      isOpen: true,
      handleType: '',
    };
  },
  components: { ImportFile, AllDetail, RepayDetail },
  watch: {
    isImport(newval, oldval) {
      if (!newval) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
  },
  mounted() {
    this.initProvince();
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA, 'areaId');
  },
  methods: {
    emitCloseHandler2(val, type) {
      this.isImport = val;
    },
    importHandler() {
      this.isImport = true;
    },
    selectChangeHandle(row) {
      if (row.length > 0) {
        this.isOpen = false;
        this.selectList = row || [];
      } else {
        this.isOpen = true;
        this.selectList = [];
      }
    },
    detailclose(val) {
      this.isAllDetail = false;
    },
    detailclose1(val) {
      this.isRepayDetail = false;
    },
    //获取顶层组织数据
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async addHandle(type) {
      if (type === 1) {
        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            let json = this.fetchParams;
            this.exportLoading = true;
            exportList(json)
              .then((response) => {
                exportExcelFile(response.data, '返利池查询');
              })
              .catch((err) => {});
            this.exportLoading = false;
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
      }
    },
    async editHandle(data, type) {
      this.detailData = data;
      if (type == 1) {
        this.isAllDetail = true;
      } else if (type == 2) {
        this.isRepayDetail = true;
      }
    },
    formatNumber(value) {
      value += '';
      if (value.slice(-1) === '.') return value;
      value = value.replace(/,\s+/g, '');
      const list = value.split('.');
      const prefix = list[0].charAt(0) === '-' ? '-' : '';
      let num = prefix ? list[0].slice(1) : list[0];
      let result = '';
      while (num.length > 3) {
        result = `, ${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
      }
      if (num) {
        result = num + result;
      }
      return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '三方票号',
          fieldName: 'billNo',
          placeholder: '请输入',
        },
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: (props) => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'RANGE_DATE',
          label: '到期时间',
          fieldName: 'expireDateBegin|expireDateEnd',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '授信额度',
          dataIndex: 'creditAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          hidden: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '保证金类型',
          dataIndex: 'depositType',
          sorter: true,
          filter: true,
          hidden: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2152'),
          render: (props) => {
            return <span>{this.createDictText(props.row.depositType, '2152')}</span>;
          },
        },
        {
          title: '保证金比例',
          dataIndex: 'depositRate',
          sorter: true,
          filter: true,
          hidden: true,
          precision: 2,
          filterType: 'input',
        },
        {
          title: '三方票号',
          dataIndex: 'billNo',
          width: 200,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '到期时间',
          dataIndex: 'expireDate',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '开票车辆数',
          dataIndex: 'allNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (props) => {
            return (
              <el-link type="warning" underline={true} onClick={() => this.editHandle(props.row, 1)}>
                {props.row.allNum}
              </el-link>
            );
          },
        },
        {
          title: '开票还款车辆数',
          dataIndex: 'allRepayNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (props) => {
            return (
              <el-link type="warning" underline={true} onClick={() => this.editHandle(props.row, 2)}>
                {props.row.allRepayNum}
              </el-link>
            );
          },
        },
        {
          title: '可用余额',
          dataIndex: 'availableAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 200,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
